package com.polimi.meteocal.business.control;

import java.util.List;

import javax.annotation.Resource;
import javax.ejb.EJBContext;
import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import com.polimi.meteocal.business.entity.Event;
import com.polimi.meteocal.business.entity.User;

/**
 * Session Bean implementation class CalendarManager
 */
@Stateless
@LocalBean
public class CalendarManager {
	
	@PersistenceContext
	private EntityManager em;
	
	@Resource
	private EJBContext _context;
    /**
     * Default constructor. 
     */
    public CalendarManager() {
      
    }
    /**
     *  Get the Logged User's Mail      
     */
    public String getLoggedUserEmail() {
		return this._context.getCallerPrincipal().getName();
	}
    
    /**
     *  Get the list of LOGGED User's Event, they include created events and events where 
     *  the user set his partecipation
     */   
    public List<Event> getUserEvents(){    	
    	List<Event> userEvents=null;
    	
		//*** ADD ACCEPTED EVENT ***
		userEvents= this.em
				.createNamedQuery(Event.FIND_FOR_USER, Event.class)
				.setParameter("user", this.getLoggedUserEmail()).getResultList();
		
    	//*** ADDING EVENT CREATED		
		userEvents.addAll(this.em
				.createNamedQuery(Event.FIND_EVENTS_CREATED,Event.class)
				.setParameter("email", this.getLoggedUserEmail()).getResultList());
		
    	return userEvents;
    }
    
    /**
     *  Get the list of ANY User's Event, they include created events and events where
     *  the user set his partecipation 
     */    
    public List<Event> getUserEvents(String userMail){    	
    	List<Event> userEvents=null;
    	
		//*** ADD ACCEPTED EVENT ***
		userEvents= this.em
				.createNamedQuery(Event.FIND_FOR_USER, Event.class)
				.setParameter("user", userMail).getResultList();
		
    	//*** ADDING EVENT CREATED		
		userEvents.addAll(this.em
				.createNamedQuery(Event.FIND_EVENTS_CREATED,Event.class)
				.setParameter("email", userMail).getResultList());
		
    	return userEvents;
    }   
    
    /**
     * Set the visibility of personal calendar     
     */
    public void setCalendarPrivacy(boolean visibility){
    	User loggedUser=this.em.find(User.class, _context.getCallerPrincipal().getName()); 
		loggedUser.setPublicvisibility(visibility);
		this.em.merge(loggedUser);
		this.em.flush();
    }
    
    /**
     *  Get the calendar visibility of logged user    
     */
    public boolean getCalendarPrivacy(String mail){
    	User user=this.em
				.createNamedQuery(User.FIND_FOR_MAIL, User.class)
				.setParameter("email", mail).getSingleResult();
    	return user.getPublicvisibility();
    }
}
